<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { useVegetableStore } from '@/stores/vegetables'
import { storeToRefs } from 'pinia'

const chartDom = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null
const vegetableStore = useVegetableStore()
const { vegetables } = storeToRefs(vegetableStore)

const initChart = () => {
  if (chartDom.value) {
    chart = echarts.init(chartDom.value)
    updateChart()
  }
}

const updateChart = () => {
  if (!chart) return
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: vegetables.value.map(v => v.name),
      textStyle: {
        color: '#4fd2dd'
      },
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLine: {
        lineStyle: {
          color: '#4fd2dd'
        }
      },
      axisLabel: {
        color: '#4fd2dd'
      }
    },
    yAxis: {
      type: 'value',
      name: '价格(元/kg)',
      nameTextStyle: {
        color: '#4fd2dd'
      },
      axisLine: {
        lineStyle: {
          color: '#4fd2dd'
        }
      },
      axisLabel: {
        color: '#4fd2dd'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(79,210,221,0.1)'
        }
      }
    },
    series: vegetables.value.map((veg, index) => ({
      name: veg.name,
      type: 'line',
      smooth: true,
      data: veg.prices,
      itemStyle: {
        color: colors[index]
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: `rgba(${colorValues[index]},0.3)`
          },
          {
            offset: 1,
            color: `rgba(${colorValues[index]},0)`
          }
        ])
      }
    }))
  }
  
  chart.setOption(option)
}

watch(vegetables, () => {
  updateChart()
}, { deep: true })

const resizeHandler = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  chart?.dispose()
})

const colors = ['#4fd2dd', '#ffc93c', '#ff6e76', '#73c0de', '#3ba272', '#fc8452']
const colorValues = [
  '79,210,221',
  '255,201,60',
  '255,110,118',
  '115,192,222',
  '59,162,114',
  '252,132,82'
]
</script>

<template>
  <div ref="chartDom" class="price-chart"></div>
</template>

<style scoped>
.price-chart {
  width: 100%;
  height: 430px;
}
</style> 